package cn.itrigger.util;

import cn.itrigger.model.InfoProperties;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.NullCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author admin
 * @date 2018/5/16
 **/
public class FreemarkerUtil {

    private static final Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_23);

    public static void config(InfoProperties infoProperties) {
        CONFIGURATION.setDefaultEncoding("utf-8");
        CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        System.out.println("freemarker模板文件路径:"+infoProperties.getFreemarkerPackage());
        CONFIGURATION.setTemplateLoader(new ClassTemplateLoader(FreemarkerUtil.class,infoProperties.getFreemarkerPackage()));
        CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE);
    }

    public static Template getTemplate(String templateName) throws IOException {
        return CONFIGURATION.getTemplate(templateName);
    }

    public static void parseFreemarker(String templateName,Map<String,Object> dataMap,File file) throws IOException, TemplateException {
        Template template = getTemplate(templateName);
        System.out.println("解析freemarker模板.....");

        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        try (Writer writer = new FileWriter(file);) {
            template.process(dataMap,writer);
        }
    }

    public static void clearCache() {
        CONFIGURATION.clearTemplateCache();
    }
}
